// 诊断查询
import React, { Component } from 'react';
import { Card, Row, Col, Input, Select, Button, Table, DatePicker, message, Icon, Divider, Popconfirm } from 'antd';
import { Util } from 'tools/index';
import { $http } from 'containers/config/https';
import store from 'store';
import Moment from 'moment';
import iconListvisits from 'assets/images/icon_listvisits.png';
import RequestForm from './CBICDDiagnosDirLinkPopu';
import CommonPagination from "../../components/pagination";

const formItemLayout = { // label 和input宽度
  labelCol: { span: 8 },
  wrapperCol: { span: 14 },
}
class ICDDiagnosDirLink extends Component {
  constructor(props) {
    super(props);
    this.state = {
      diagnosisDesc: undefined,
      startDate: Moment(),
      endDate: undefined,
      locList:[],
      locID:'',
      directoryID:'',
      basicHeight: 0,
      tableData: [],
      page: 1,
      pageSize: 20,
      total: 0,
      loading: false,
      insuType: '',
      medicalType: [],
      visible: false,
      userInfo: JSON.parse(window.sessionStorage.userData),
      proData:{},
      ICDObj: {}
    };

    this.columns = [
      {
        title: '病种名称',
        dataIndex: 'directoryDesc',
        width: 120,
        align: 'center'
      },
      {
        title: '科室名称',
        dataIndex: 'locDesc',
        width: 220,
        align: 'center'
      },
      {
        title: 'ICD10诊断代码',
        dataIndex: 'iCDCode',
        width: 120,
        align: 'center'
      },
      {
        title: 'ICD10诊断描述',
        dataIndex: 'iCDDesc',
        width: 120,
        align: 'center'
      },
      {
        title: '生效日期',
        dataIndex: 'startDate',
        width: 120,
        align: 'center'
      },
      {
        title: '失效日期',
        dataIndex: 'stopDate',
        width: 120,
        align: 'center'
      },
      {
        title: '操作',
        align: "center",
        width: 100,
        fixed: 'right',
        render: (text, record) => (
            <span>
            <Icon type="edit" style={{ color: '#108EE9' }}></Icon>
            <span className='span' onClick={() => this.handleCompile(record)}>编辑</span>
            <Divider type="vertical"></Divider>
            <Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={() => this.handleCompile(record, "2")} >
              <span className='span' style={{ color: "red" }}>删除</span>
            </Popconfirm>
          </span>
        ),
      }

    ]
  }

  componentDidMount() {
    this.setState({ basicHeight: document.getElementById("diagnostic-query").clientHeight }, () => {
      this.getLocSelectData();
      this.loadDiagnosDirs();
      this.handleQuery()
      // setTimeout(() => {
      //   this.myRef1.current.focus();
      // }, 300)
    });
  }

  // 诊断名称
  handleDiagnosisDescChange = e => {
    this.setState({ diagnosisDesc: e.target.value })
  }
  handleChangeSelect = e => {
    this.setState({ insuType: e })
  }
  // 开始日期
  handleStartDateChange = e => {
    this.setState({ startDate: e })
  }

  // 开始日期
  handleEndDateChange = e => {
    this.setState({ endDate: e })
  }

  // 查询
  handleQuery = () => {
    this.setState({ page: 1 ,loading:true}, () => {
      this.getTableData();
    })
  }
  // 重置表单
  resetFields = () => {
    this.setState({
      proData:'',
      locID:'',
      diagnosisDesc:'',
      directoryID:'',
      ICDObj: {}
    })

  };
  // 编辑
  handleCompile = (record, num) => {
    if (num == "2") {
      console.log("record",record)
      if(record.ID===""){
        return;
      }
      let {userInfo}=this.state
      let data = {
        params: [{
          ID: record.rowId,
          updateUserID:userInfo.userID
        }],
      }
      let that = this
      $http.post("urlS", this, {
        code: "01070003",
        data: data,
        success: function (res) {
          if (+res.errorCode === 0) {
            message.success("删除成功")
            that.resetFields();
            that.handleQuery();
          }
        }
      })
    }
    else {
      var ICDObj={id:record.iCDID,code:record.iCDCode,descripts:record.iCDDesc}
      this.setState({ proData: record,ICDObj:ICDObj },()=>{
        this.showPopu();
      });

    }
  }
  loadMedicalType() {
    var params = {
      params: [{}]
    }
    $http.post('urlDeault', this, {
      code: "05100389",
      data: params,
      success: function (res) {
        if (res.errorCode == '0') {
          this.setState({
            medicalType: res.result,
          })
        }
      }
    });
  }

  /**
   * @ByYQL:分页功能
   * 添加分页功能
   * Create 2021-11-30
   */
      // 条数改变的回调
  handleShowSizeChange = (current, size) => {
    this.setState({ page: current, pageSize: size,loading:true }, () => {
      this.getTableData();
    });
  }

  //页码改变的回调
  handlePageChange = (page, pageSize) => {
    this.setState({ page: page, pageSize ,loading:true}, () => {
      this.getTableData();
    });
  }
// 获取科室下拉数据
getLocSelectData = () => {
  let { userInfo } = this.state;
  var params = {
      params: [{
          hospID: userInfo && userInfo.hospID ? userInfo.hospID : "",
      }]
  }
  $http.post('urlDeault', this, {
      code: "01050008",
      data: params,
      success: function (res) {
          if (+res.errorCode === 0) {
              let locList = res.result && res.result.data && res.result.data.length > 0 ? res.result.data : [];
              this.setState({
                  locList,
                  locID: res.result && res.result.defaultLocID ? String(res.result.defaultLocID) : undefined
              })
          }
      }
  });
}
// 获取下拉框
loadDiagnosDirs() {
  var params = {
      params: [{}]
  }
  $http.post('urlDeault', this, {
      code: "01070004",
      data: params,
      success: function (res) {
          if (res.errorCode == '0') {
              this.setState({
                  directoryList: res.result.data,
              })
          }
      }
  });
}
  // 获取列表数据
  getTableData = () => {
    let { diagnosisDesc, directoryID, startDate, locID, page, pageSize } = this.state
    console.log("startDate", startDate)
    var params = {
      params: [{
        diagnosisDesc: diagnosisDesc || '',
        directoryID: directoryID || '',
        locID: locID || '',
        // startDate: startDate ? Moment(startDate).format('YYYY-MM-DD') : Moment(new Date()).format('YYYY-MM-DD'),
        // endDate: endDate || '',
      }],
      pagination: [{
        pageSize,
        currentPage: page
      }]
    }
    $http.post('urlDeault', this, {
      code: "01070001",
      data: params,
      success: function (res) {
        if (res.errorCode == '0') {
          this.setState({
            tableData: res.result.rows,
            total:res.result.total,
            loading:false
          })
        }else{
          message.warning(res.errorMessage)
          this.setState({
            loading:false
          })
        }
      }
    });
  }
  //弹框
  showPopu = () => {
    let {proData,ICDObj}=this.state
    // console.log("insObj11111111111111",insObj)
    // console.log("ICDObj22222222222222",ICDObj)
    this.childSelect.showModal(proData,ICDObj);
  };
  addNew=()=>{
    this.childSelect.showModal();
  }
  onSelectRef = (ref) => {
    this.childSelect = ref;
  };
  render() {
    let { diagnosisDesc, startDate, endDate, basicHeight, tableData, page,pageSize, total, loading } = this.state;
    
    // 科室
    let locOption = [];
    this.state.locList && this.state.locList.map((item, index) => {
        locOption.push(<Option key={index} value={String(item.id)} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
    })

    // 集团病种
    let directoryOption = [];
    this.state.directoryList && this.state.directoryList.map((item, index) => {
      directoryOption.push(<Option key={index} value={String(item.id)} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
    })

    return (
        <div className="diagnostic-query">
          <Row id="diagnostic-query" style={{ padding: '0 24px' }}>
            <Col span={20} className="input-padding-right">
              <Row style={{ marginBottom: '20px' }}>
                病种名称：
                <Select 
                  style={{ width: "150px", margin: '22px 10px 0 0' }}
                  showSearch
                  allowClear 
                  optionFilterProp="seatchprop" placeholder='请选择病种名称' onChange={Util.handleSelectChange.bind(this, 'directoryID')}>
                    {directoryOption}
                </Select>
                诊断名称:
                <Input
                    style={{ width: "150px", margin: '22px 10px 0 0' }}
                    placeholder="请输入"
                    allowClear
                    onChange={this.handleDiagnosisDescChange} value={diagnosisDesc}
                    onPressEnter={this.diagnosisDescOnPressEnter} id="diagnosisDesc"
                />
                科室名称:
                <Select 
                  style={{ width: "150px", margin: '22px 10px 0 0' }}
                  showSearch allowClear optionFilterProp="seatchprop" placeholder='请选择科室' onChange={Util.handleSelectChange.bind(this, 'locID')}>
                    {locOption}
                </Select>
                <Button style={{ marginTop: '8px' }} onClick={this.handleQuery}>查询</Button>
                <Button style={{ marginTop: '8px', marginLeft: '8px' }} onClick={this.addNew}>新增</Button>
              </Row>
            </Col>
            <Col span={4} style={{ textAlign: 'right' }}>

            </Col>
          </Row>
          <div style={{ height: '6px', background: 'rgba(240, 242, 245, 1)', width: '100%' }}></div>
          <Card
              size="small"
              title={<div className="card-title-left-img"><img src={iconListvisits} alt="" />诊断列表</div>}
          >
            <div>
              <Table
                  columns={this.columns}
                  dataSource={tableData}
                  style={{ height: store.getState().tableHeight.y + 136 - basicHeight + 'px', }}
                  scroll={{ x: 480, y: store.getState().tableHeight.y + 80 - basicHeight }}
                  // rowSelection={rowSelection}
                  onRow={this.onClickRowPublic}
                  rowClassName={this.setRowClassNamePublic}
                  // onHeaderRow={() => {
                  //   return {
                  //     onDoubleClick: () => {
                  //       this.columnRef.onOpenModel()
                  //     },
                  //   };
                  // }}
                  bordered
                  rowKey={(data) => {
                    return data.rowId
                  }}
                  loading={loading}
                  pagination={false}
                  className="table-body-height" />

              {/*新增分页功能*/}
              <CommonPagination current={page} total={total} search="search" pageSize={pageSize}
                                onShowSizeChange={this.handleShowSizeChange} complete={true} dataSource={tableData} size='small'
                                loading={loading} onChange={this.handlePageChange} />
            </div>
          </Card>
          <RequestForm onRef={this.onSelectRef} handleThis={this} />
        </div>
    );
  }
}

export default ICDDiagnosDirLink;
